package com.walle.gatewayserver.fallback;

import com.alibaba.fastjson.JSON;
import com.walle.gatewayserver.base.CodeContant;
import com.walle.gatewayserver.vo.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * zuul错误处理
 * @author walle
 */
@Component
@Slf4j
public class CustomZuulFallbackHandler implements FallbackProvider {

	@Override
	public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
		// TODO Auto-generated method stub
		return new ClientHttpResponse() {
			
			@Override
			public HttpHeaders getHeaders() {
				HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                return headers;
			}
			
			@Override
			public InputStream getBody() throws IOException {
				
				ApiResult apiRsult = new ApiResult<>(CodeContant.SERVER_ERROR.getCode(), CodeContant.SERVER_ERROR.getMsg());
				
				log.error("========= 访问服务端异常：",cause.getMessage());
				// 当出现服务调用错误之后返回的数据内容
				return new ByteArrayInputStream(JSON.toJSONString(apiRsult).getBytes());
			}
			
			@Override
			public String getStatusText() throws IOException {
				// TODO Auto-generated method stub
				return HttpStatus.OK.getReasonPhrase();
			}
			
			@Override
			public HttpStatus getStatusCode() throws IOException {
				// TODO Auto-generated method stub
				return HttpStatus.OK;
			}
			
			@Override
			public int getRawStatusCode() throws IOException {
				// TODO Auto-generated method stub
				return HttpStatus.OK.value();
			}
			
			@Override
			public void close() {
				// TODO Auto-generated method stub
				
			}
		} ;
	}

	@Override
	public String getRoute() {
		// TODO Auto-generated method stub
		return "*";
	}

}
